const express = require("express");
const fs = require("fs");
const path = require("path");
const cors = require("cors");
const app = express();
const multer = require("multer");
const request = require("request");

app.use(express.json()); // 解析 JSON 类型的请求体
app.use(cors()); // 添加 cors 中间件

app.use(express.static(path.join(__dirname, "uploadResume"))); // 访问pdf

const userDbPath = path.resolve(__dirname, "./data/users.json");
const userResumeDbPath = path.resolve(__dirname, "./data/userResumes.json");

app.post("/login", (req, res) => {
  const { username, password } = req.body;
  const userDbFileContent = fs.readFileSync(userDbPath, "utf8");
  const users = userDbFileContent ? JSON.parse(userDbFileContent, "utf8") : [];
  // 查找用户是否存在
  const user = users.find(
    (user) => user.username === username && user.password === password
  );

  if (!user) {
    return res
      .status(200)
      .json({ code: 401, message: "Invalid username or password" });
  }

  res.json({ code: 0, message: "Login successful", username: user.username });
});

app.post("/register", (req, res) => {
  const newUser = req.body;
  const userDbFileContent = fs.readFileSync(userDbPath, "utf8");
  const users = userDbFileContent ? JSON.parse(userDbFileContent, "utf8") : [];
  // 检查是否存在相同用户名的用户
  const existingUser = users.find((user) => user.username === newUser.username);
  if (existingUser) {
    return res
      .status(200)
      .json({ code: 400, message: "Username already exists" });
  }

  // 添加新用户
  users.push(newUser);
  fs.writeFileSync(userDbPath, JSON.stringify(users, null, 2));

  res.json({ code: 0, message: "User registered successfully" });
});

// 自定义multer storage，用来设置上传的文件如何被存储
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploadResume/");
  },
  filename: function (req, file, cb) {
    // 从请求中获取username
    const fliename = file.originalname.split(".")[0];
    // 生成6位随机数
    const randomStr = Math.random().toString(36).substring(2, 8);
    // 获取文件原始扩展名
    const fileExtension = path.extname(file.originalname);
    // 设置文件名为 fliename + 随机6位数字 + 文件扩展名
    const filename = fliename + "-" + randomStr + fileExtension;
    req.body.newFileName = filename;
    cb(null, filename);
  },
});

const upload = multer({
  storage: storage, // 指定上传的文件存储在uploadResume目录下
  limits: { fileSize: 5 * 1024 * 1024 }, // 设置文件大小限制为5MB
  fileFilter: function (req, file, cb) {
    // 设置文件类型，只接受pdf|doc|docx|txt文件
    const filetypes = /pdf|doc|docx|txt/; // 设置文件类型
    const extname = filetypes.test(file.originalname);
    const mimetype = filetypes.test(file.mimetype);
    if (mimetype && extname) {
      return cb(null, true);
    }
    cb(
      new Error(
        "Error: File upload only supports the following filetypes - " +
          filetypes
      )
    );
  },
});
// 上传文件
app.post(
  "/upload",
  upload.single("file"),
  (req, res, next) => {
    getResumeInfo(req.body.newFileName)
      .then((rsp) => {
        if (rsp.status.code !== 200) {
          return res.status(200).json({ code: 500, message: rsp.status.msg });
        }
        const username = req.body.username;
        const result = rsp.result;
        result.filePath = req.body.newFileName;
        const userResumeDbFileContent = fs.readFileSync(
          userResumeDbPath,
          "utf8"
        );
        const users = userResumeDbFileContent
          ? JSON.parse(userResumeDbFileContent, "utf8")
          : {};
        const userResumes = users[username] || [];
        userResumes.push(result);
        users[username] = userResumes;
        fs.writeFileSync(userResumeDbPath, JSON.stringify(users, null, 2));

        res.status(200).json({
          code: 0,
          message: "File uploaded successfully",
          data: result,
        });
      })
      .catch((err) => {
        res.status(200).json({ code: 500, message: err || "未知错误" });
      });
  },
  (err, req, res, next) => {
    if (err instanceof multer.MulterError) {
      res.status(200).json({ code: 400, message: err.message });
    } else if (err) {
      res.status(200).json({ code: 500, message: err.message || "未知错误" });
    }
  }
);

app.get("/getUserResume", (req, res) => {
  const { username } = req.query;
  const userResumeDbFileContent = fs.readFileSync(userResumeDbPath, "utf8");
  const users = userResumeDbFileContent
    ? JSON.parse(userResumeDbFileContent, "utf8")
    : {};
  const userResumes = users[username] || [];
  res.json({
    code: 0,
    message: "success",
    data: userResumes[userResumes.length - 1],
  });
});

const resumeApiUrl = "http://resumesdk.market.alicloudapi.com/ResumeParser";
const appCode = "替换为自己的appcode"; // 替换为自己的appcode
// 简历分析
const getResumeInfo = (file_name) => {
  const filePath = path.resolve(__dirname, `./uploadResume/${file_name}`);
  return new Promise((resolve, reject) => {
    const options = {
      url: resumeApiUrl,
      headers: {
        contentType: "application/json",
        Authorization: `APPCODE ${appCode}`,
      },
      json: {
        file_cont: Buffer.from(fs.readFileSync(filePath)).toString("base64"),
        file_name: file_name,
        need_avatar: 0,
        version: 1,
      },
    };

    request.post(options, function (error, response, body) {
      if (!error && response.statusCode == 200) {
        // 请求成功的处理逻辑
        resolve(body);
      } else {
        console.log(error); // 请求失败的处理逻辑
        reject(error);
      }
    });
  });
};

app.listen(8081, () => {
  console.log("Server is running on port 8081");
});
